package com.huxiu;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.huxiu.net.GsonRequest;
import com.huxiu.net.NetworkConstants;
import com.huxiu.net.NetworkHelper;
import com.huxiu.net.model.MyFavoriteDataList;
import com.huxiu.net.responses.BaseResponse;
import com.huxiu.net.responses.MyFavoriteListResponse;
import com.huxiu.utils.Constants;
import com.huxiu.utils.UmenEvent;
import com.huxiu.utils.LogUtil;
import com.huxiu.utils.Utils;
import com.huxiu.view.RefreshListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.umeng.analytics.MobclickAgent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class ShouCangDetailActivity extends BaseActivity {
    @ViewInject(R.id.shoucang_name)
    private TextView name;
    @ViewInject(R.id.shoucang_list)
    private RefreshListView list;
    @ViewInject(R.id.footer_xiugai)
    private ImageView footer_xiugai;
    @ViewInject(R.id.footer_shanchu)
    private ImageView footer_shanchu;

    private MyAdapter adapter;
    private String uid;
    private String cid;
    private String strName;

    private ShouCangDetailActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shou_cang_detail);
        ViewUtils.inject(this);
        instance=this;
        footer_xiugai.setVisibility(View.VISIBLE);
        footer_shanchu.setVisibility(View.VISIBLE);
        String dataStr = getIntent().getStringExtra("favorite_data");
        String titleStr = getIntent().getStringExtra("favorite_title");
        MyFavoriteDataList mData = new Gson().fromJson(dataStr, MyFavoriteDataList.class);
        uid = mData.uid;
        cid = mData.cid;
        if (TextUtils.isEmpty(titleStr)) {
            strName = mData.name;
        } else {
            strName = titleStr;
        }
        name.setText(strName);
        list.setOnRefreshingListener(new MyOnRefreshingListener());
        getDataFromServer();
    }

    //    @ViewInject(R.id.back)
    //    private ImageView back;

    @OnClick({R.id.back, R.id.footer_xiugai, R.id.footer_shanchu})
    public void mOnClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.footer_xiugai:
                dialogXiuGai();
                break;
            case R.id.footer_shanchu:
                dialogDelete();
                break;
        }
    }


    private void dialogXiuGai() {
        View view = View.inflate(this, R.layout.dialog_edittext, null);
        final EditText et = (EditText) view.findViewById(R.id.et);
        et.setHint(strName);
        new AlertDialog.Builder(this).setTitle(getString(R.string.mine_shoucang_xiugai))
                .setView(view)
                .setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        if (TextUtils.isEmpty(et.getText().toString())) {
                            Utils.showToast("文件名不能为空");
                            return;
                        }
                        strName = et.getText().toString();
                        changName();
                    }
                }).setNeutralButton(getString(android.R.string.cancel), null).show();
    }

    private void changName() {
        String url = NetworkConstants.UPDATE_FAVORITE_CATEGORY_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("name", strName);
        params.put("uid", uid);
        params.put("cid", cid);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, true, params,
                new Response.Listener<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response) {
                        if (response.isSuccess()) {
                            Utils.runOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    name.setText(strName);
                                    UmenEvent.UmengEventMap(instance, UmenEvent.APP_USERCENTER_MYCOLLECT, UmenEvent.MY_COLLECT_CHANGE);
                                }
                            });
                            Intent data = new Intent();//需要返回数据时用
                            data.putExtra("favorite_title", strName);
                            setResult(2, data);

                        } else {
                            Utils.showToast(response.error.message);
                        }
                    }
                }, mErrorListener);
        mQueue.add(request);
    }

    protected void dialogDelete() {
        new AlertDialog.Builder(this).setMessage(getString(R.string.mine_shoucang_shanchu))
                .setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteList();
                    }
                }).setNeutralButton(getString(android.R.string.cancel), null).show();
    }

    private void deleteList() {
        String url = NetworkConstants.DELETE_FAVORITE_CATEGORY_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", uid);
        params.put("cid", cid);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, true, params,
                new Response.Listener<BaseResponse>() {
                    @Override
                    public void onResponse(BaseResponse response) {
                        if (response.isSuccess()) {
                            if (lists != null && lists.size() != 0) {
                                lists.clear();
                            }
                            parseListJson();
                            setResult(RESULT_OK);
                            UmenEvent.UmengEventMap(instance, UmenEvent.APP_USERCENTER_MYCOLLECT, UmenEvent.MY_COLLECT_DEL);
                            finish();
                        } else {
                            Utils.showToast(response.error.message);
                        }
                    }
                }, mErrorListener);
        mQueue.add(request);
    }


    private boolean isRefresh = false;// 当前是否是下拉刷新
    private boolean isLoadMore = false;// 当前是否是加载更多

    class MyOnRefreshingListener implements RefreshListView.OnRefreshingListener {
        @Override
        public void onRefreshing() {
            isRefresh = true;
            // 下拉刷新业务
            getDataFromServer();
        }

        @Override
        public void onLoadingMore() {
            if (currentPage < totalPages) {
                isLoadMore = true;
                // 加载更多业务
                getMoreDataFromServer();
            } else {
                list.loadMoreFinished();
//                Utils.showToast(R.string.no_more);
                Toast.makeText(ShouCangDetailActivity.this, R.string.no_more, Toast.LENGTH_SHORT).show();
            }
        }

    }

    //上拉加载
    private void getMoreDataFromServer() {
        loadList(currentPage + 1);
    }

    //下拉刷新
    private void getDataFromServer() {
        loadList(1);
    }

    private int currentPage = 1;
    //获取推荐页列表页数据
    private List<MyFavoriteDataList> lists = new ArrayList<>();
    private int totalPages = 0;

    private void loadList(final int page) {
        String url = NetworkConstants.MY_FAVORITE_ARTICLE_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        params.put("uid", uid);
        LogUtil.i("qcl3", "uid" + uid);
        params.put("cid", cid);
        LogUtil.i("qcl3", "cid" + cid);
        GsonRequest<MyFavoriteListResponse> request = new GsonRequest<>(url, Request.Method.POST,
                MyFavoriteListResponse.class, true, params,
                new Response.Listener<MyFavoriteListResponse>() {
                    @Override
                    public void onResponse(MyFavoriteListResponse response) {
                        if (response.isSuccess()) {
                            if (page == 1) {
                                lists.clear();
                            }
                            Collections.addAll(lists, response.data.datalist);
                            currentPage = response.data.cur_page;
                            totalPages = response.data.total_page;
                            parseListJson();
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                list.refreshFinished(true);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                list.loadMoreFinished();
                                isLoadMore = false;

                            }
                        } else {
                            Utils.showToast(response.error.message);
                            // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                            if (isRefresh) {
                                list.refreshFinished(false);
                                isRefresh = false;
                            } else if (isLoadMore) {
                                list.loadMoreFinished();
                                isLoadMore = false;
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(R.string.generic_failure);
                // 如果当前是下拉刷新访问的网络，恢复下拉刷新界面
                if (isRefresh) {
                    list.refreshFinished(false);
                    isRefresh = false;
                } else if (isLoadMore) {
                    list.loadMoreFinished();
                    isLoadMore = false;
                }
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
    }

    private void parseListJson() {
        if (!isLoadMore) {
            adapter = new MyAdapter();
            list.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return lists.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(ShouCangDetailActivity.this, R.layout.item_shoucang_list, null);
            }
            //获取holder对象
            HomeHolder holder = HomeHolder.getHolder(convertView);
            //设置数据
            final MyFavoriteDataList mItem = lists.get(position);
            holder.title.setTextColor(0xff383838);
            holder.title.setText(mItem.title);
            holder.time.setText(Utils.getDateString(mItem.favorite_time));
            holder.listItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ShouCangDetailActivity.this, DetailActivity.class);
                    intent.putExtra(Constants.TUIJIAN_ITEM_KEY, mItem.toString());
                    startActivity(intent);
                }
            });
            return convertView;
        }


    }

    //下面的写法是大神的写法，以后可以用这个。
    static class HomeHolder {
        TextView title, time;
        LinearLayout listItem;

        public HomeHolder(View convertView) {
            title = (TextView) convertView.findViewById(R.id.shoucang_item_title);
            time = (TextView) convertView.findViewById(R.id.shoucang_item_time);
            listItem = (LinearLayout) convertView.findViewById(R.id.my_favorite_list_item);
        }

        public static HomeHolder getHolder(View convertView) {
            HomeHolder holder = (HomeHolder) convertView.getTag();
            if (holder == null) {
                holder = new HomeHolder(convertView);
                convertView.setTag(holder);
            }
            return holder;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }

}
